package com.qf.service.impl;

import com.auth0.jwt.JWT;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.qf.entity.TlPerson;
import com.qf.entity.TlUser;
import com.qf.mapper.PersonMapper;
import com.qf.mapper.UserMapper;
import com.qf.service.PersonService;
import com.qf.utils.Mycode;
import com.qf.utils.RedisKey;
import com.qf.utils.ResultMsg;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

@Service
public class PersonServiceImpl extends ServiceImpl<PersonMapper, TlPerson> implements PersonService {

    @Autowired
    RedisTemplate redisTemplate;

    @Autowired(required = false)
    UserMapper userMapper;

    @Autowired(required = false)
    PersonMapper personMapper;
    /**
     * 查询乘车人
     * @return
     */
    @Override
    public ResultMsg findAllPerson(HttpServletRequest request) {
        String uuid = request.getHeader("token");
        Object o = redisTemplate.boundValueOps(RedisKey.LOGIN_USER+uuid).get();
        if (o == null)
            return ResultMsg.ERROR(Mycode.NOTLOGIN_ERRO);
        String token = (String) o;
        List<String> audience = JWT.decode(token).getAudience();
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.eq("user_name", audience.get(0));
        TlUser tlUser = userMapper.selectOne(queryWrapper);
        QueryWrapper<TlPerson> wrapper = new QueryWrapper<>();
        wrapper.eq("user_id",tlUser.getUserId());
        List<TlPerson> list = super.list(wrapper);
        return ResultMsg.SUCCESS(list);
    }

    /**
     * 新增和修改
     * @param tlPerson 乘车人对象
     * @return 0:失败  1:成功
     */
    @Override
    public ResultMsg modify(TlPerson tlPerson,HttpServletRequest request) {
        String uuid = request.getHeader("token");
        Object o = redisTemplate.boundValueOps(RedisKey.LOGIN_USER+uuid).get();
        if (o == null)
            return ResultMsg.ERROR(Mycode.NOTLOGIN_ERRO);
        String token = (String) o;
        List<String> audience = JWT.decode(token).getAudience();
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.eq("user_name", audience.get(0));
        TlUser tlUser = userMapper.selectOne(queryWrapper);
        tlPerson.setUserId(tlUser.getUserId());
        boolean b = super.saveOrUpdate(tlPerson);
        if (b)
            return ResultMsg.SUCCESS();
        return ResultMsg.ERROR(Mycode.MODIFY_ERRO);
    }

    @Override
    public ResultMsg insert(Integer userId, String personName, String personCard, String personTel, Integer personFlag) {
        int insert = personMapper.insert(userId, personName, personCard, personTel, personFlag);
        return ResultMsg.SUCCESS();
    }

}
